package br.com.treinamento.gestaoExperienciaProfissonal.dao;

import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.persistence.EntityManager;

import br.com.treinamento.gestaoExperienciaProfissonal.util.JPAUtil;

@SuppressWarnings("unchecked")
public class GenericDAO<T> {
	private EntityManager entityManager;
	 
    public GenericDAO() {
        this.entityManager = JPAUtil.getEntityManager();
    }
  
    public void save(T entity) {
        entityManager.persist(entity);
    }
 
    public void update(T entity) {
        entityManager.merge(entity);
    }
    
    public T find(Integer id) {
        return (T) entityManager.find(getTypeClass(), id);
    }
 
    public T findDetach(Integer id) {
        T object = (T) find(id);
        entityManager.detach(object);
        return object;
    }
    
    public void delete(T entity) {
    	entity = entityManager.merge(entity);
        entityManager.remove(entity);
    }
 
    public List<T> listar() {
        return entityManager.createQuery("FROM " + getTypeClass().getSimpleName() + " o").getResultList();
    }
 
    private Class<?> getTypeClass() {
        Class<?> clazz = (Class<?>) ((ParameterizedType) this.getClass()
                .getGenericSuperclass()).getActualTypeArguments()[0];
        return clazz;
    }

}
